<template>
  <view class="bank">
    <view class="bank-box">
      <u-form :model="form" ref="uForm" :label-width="152">
        <u-form-item label="持卡人姓名" class="form-item-box">
          <u-input v-model="form.userName" placeholder="" disabled />
        </u-form-item>
        <u-form-item label="身份证号" class="form-item-box">
          <u-input
            disabled
            maxlength="18"
            v-model="form.userIdcardNo"
            placeholder=""
          />
        </u-form-item>
        <u-form-item
          ref="bankCardNo"
          prop="bankCardNo"
          label="银行卡号"
          class="form-item-box"
          required
        >
          <u-input
            type="number"
            v-model="form.bankCardNo"
            @input="handleBankCardNo"
            placeholder="请输入银行卡号"
          />
          <u-icon
            slot="right"
            name="camera"
            @click="chooseBank"
            size="36"
          ></u-icon>
        </u-form-item>
        <u-form-item
          ref="bankShortName"
          prop="bankShortName"
          label="银行名称"
          class="form-item-box"
          required
        >
          <u-input v-model="form.bankShortName" placeholder="请输入银行名称" />
        </u-form-item>
        <u-form-item label="支行查询" class="form-item-box">
          <u-search
            placeholder="请输入开户银行"
            shape="square"
            v-model="keyword"
            @custom="search"
          ></u-search>
          <u-select
            v-if="bankShortNamelist.length"
            v-model="showbankShortNameList"
            mode="single-column"
            :list="bankShortNamelist"
            @confirm="confirm"
          ></u-select>
        </u-form-item>
        <u-form-item
          ref="bankName"
          prop="bankName"
          label="支行名称"
          class="form-item-box"
          required
        >
          <u-input v-model="form.bankName" disabled placeholder="" />
        </u-form-item>
      </u-form>
    </view>
    <u-keyboard
      mode="card"
      @change="keyboardChange1"
      :dot-enabled="false"
      :tooltip="false"
      :mask="false"
      :safe-area-inset-bottom="true"
      @backspace="keyboardBackspace1"
      v-model="showKeyboard1"
    ></u-keyboard>
    <view class="submit-btn" @click="handleSubmit">确定</view>
    <view class="alert"
      >温馨提示：如果您需要查询支行名称，可以使用手机银行查询。另外，您也可以拨打银行客服电话查询，以确认具体支行信息。为确保填写信息准确无误，请仔细核对填写的相关信息，确认无误后点击“确定”按钮，即可添加成功。</view
    >
  </view>
</template>
<script>
import httpEnum from './../../common/httpEnum.js'
import wPicker from '@/components/w-picker/w-picker.vue'
export default {
  components: {
    wPicker,
  },
  data() {
    return {
      showKeyboard1: false,
      showCity: false,
      form: {
        userIdcardNo: '',
        bankCardNo: '',
        bankShortName: '',
        bankName: '',
        bankCode: '',
        bankPlace: '',
      },
      timer: null,
      time: 60,
      rules: {
        bankCardNo: [
          {
            required: true,
            pattern: /^([1-9]{1})(\d{15}|\d{16}|\d{18})$/,
            message: '请输入正确的银行卡号',
            trigger: ['change', 'blur'],
          },
        ],
        bankShortName: [
          {
            required: true,
            message: '请输入银行名称',
            trigger: ['change', 'blur'],
          },
        ],
        bankName: [
          {
            required: true,
            message: '请选择银行',
            trigger: ['change', 'blur'],
          },
        ],
      },
      showBankType: false,
      bankTypeList: [],
      uploadUrl:
        httpEnum.baseUploadUrl + '/freight-business/ocr/recognize/bankCard',
      uploadData: {
        bucketName: 'logistics-control-platform',
        folderName: 'driverPic',
      },
      showbankShortNameList: false,
      bankShortNamelist: [],
      keyword: '',
      bankId: undefined,
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  onLoad(options) {
    this.bankId = options.bankId
    this.getDictData('bank_card_type')
  },
  onShow() {
    this.getDetailsData(this.bankId)
  },
  computed: {
    codeText() {
      if (!this.timer) {
        return '获取验证码'
      } else {
        return `${this.time}s后重新获取`
      }
    },
  },
  methods: {
    search(val) {
      if (!val) {
        this.$api.msg('查询前请输入开户银行')
      } else {
        this.handleBankCard(val)
      }
    },
    confirm(e) {
      this.form.bankCode = e[0].value
      this.form.bankName = e[0].label
      this.triggerSingleFieldValidate('bankName')
    },
    throttle(fn, delay) {
      let flag = true
      return function () {
        if (flag) {
          steTimeout(() => {
            fn.call(this)
            flag = true
          }, 500)
        }
        flag = false
      }
    },
    async handleBankCard(val) {
      const { code, result, message } = await this.$u.get(
        '/freight-business/freightDriver/driver/bankInfo',
        {
          bankName: this.form.bankShortName,
          content: val,
        }
      )
      if (code === '0') {
        this.bankShortNamelist = []
        this.showbankShortNameList = true
        if (!result.length) {
          this.$api.msg('未查询到开户银行')
        } else {
          result.forEach((item) => {
            this.bankShortNamelist.push({
              value: item.bankCode,
              label: item.bankName,
            })
          })
        }
      } else {
        this.$api.msg(message)
      }
    },
    async handleBankCardNo(e) {
      const reg = /^([1-9]{1})(\d{15}|\d{16}|\d{18})$/
      if (reg.test(e)) {
        const { code, result, message } = await this.$u.get(
          '/freight-business/payIcbc/driver/queryBankInfo',
          {
            cardNo: this.form.bankCardNo,
          }
        )
        if (code === '0') {
          this.bankShortNamelist = []
          this.form.bankShortName = result.bankShortName
          // this.handleBankCard(this.form.bankShortName)
        } else {
          this.$api.msg(message)
        }
      }
      this.triggerSingleFieldValidate('bankCardNo')
    },
    //触发校验
    triggerSingleFieldValidate(refName) {
      this.$refs[refName].onFieldChange()
    },
    keyboardChange1(e) {
      this.triggerSingleFieldValidate('userIdcardNo')
      if (this.form.userIdcardNo.length < 18) {
        this.form.userIdcardNo = this.form.userIdcardNo + e
        this.triggerSingleFieldValidate('userIdcardNo')
      }
    },
    keyboardBackspace1() {
      if (
        this.form.userIdcardNo.length &&
        this.form.userIdcardNo.length <= 18
      ) {
        this.form.userIdcardNo = this.form.userIdcardNo.slice(
          0,
          this.form.userIdcardNo.length - 1
        )
        this.triggerSingleFieldValidate('userIdcardNo')
      }
    },
    // 查询字典
    async getDictData(type) {
      const { code, result, message } = await this.$u.get(
        `/freight-auth/dictValue/type/${type}`
      )
      if (code === '0') {
        if (type == 'bank_card_type') {
          this.bankTypeList = result.map((item) => {
            return {
              label: item.labelDefault,
              value: item.value,
            }
          })
        }
      } else {
        this.$api.msg(message)
      }
    },
    onConfirm(e) {
      this.form.bankPlace = e.result
    },
    onCancel() {
      this.showCity = false
    },
    sendCode() {
      if (this.timer) return
      if (this.form.phone) {
        this.timer = setInterval(() => {
          this.time--
          if (this.time < 1) {
            clearInterval(this.timer)
            this.timer = null
            this.time = 60
          }
        }, 1000)
      } else {
        this.$api.msg('请先输入手机号码')
      }
    },
    handleSubmit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.submitUpData(this.form)
        } else {
          this.$api.msg('请填写相关信息')
        }
      })
    },
    chooseBank() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          uni.uploadFile({
            url: this.uploadUrl,
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: this.uploadData,
            success: ({ data, statusCode }) => {
              const j = JSON.parse(data)
              if (j.code == '0') {
                this.form.bankCardNo = j.result.cardNumber
                this.form.bankShortName = j.result.bankName
                // this.form.bankName = this.bankTypeList.find(
                //   (item) => j.result.bankName == item.label
                // )
                //   ? this.bankTypeList.find(
                //       (item) => j.result.bankName == item.label
                //     ).value
                //   : ''
              } else {
                this.$api.msg(j.message)
              }
            },
            fail: (error) => {
              console.log(error)
            },
          })
        },
      })
    },
    async getDetailsData(val) {
      const { code, result, message } = await this.$u.get(
        '/freight-business/freightUserBank/details',
        {
          bankId: val,
        }
      )
      if (code === '0') {
        result.bankPlace = ''
        this.form = result
      } else {
        this.$api.msg(message)
      }
    },
    async submitUpData(val) {
      delete val.createAt
      let data = {
        ...val,
      }
      const { code, result, message } = await this.$u.post(
        '/freight-business/freightUserBank/update',
        data
      )
      if (code === '0') {
        this.$api.msg('银行卡修改成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      } else {
        this.$api.msg(message)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.bank {
  min-height: 100vh;
  background: #f6f6f6;
  padding: 30rpx;
  box-sizing: border-box;
  &-box {
    width: 690rpx;
    background: #ffffff;
    border-radius: 10rpx;
    padding: 0 24rpx;
    box-sizing: border-box;
  }
}
.code {
  width: 140rpx;
  height: 48rpx;
  background: #387cf9;
  border-radius: 8rpx;
  text-align: center;
  line-height: 48rpx;
  color: #fff;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  &.disabled {
    background: #eee;
    width: 180rpx;
  }
}
.submit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 80rpx;
  width: 690rpx;
  height: 80rpx;
  margin: 0 auto;
  background: #378afb;
  border-radius: 10rpx;
  text-align: center;
  line-height: 80rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  color: #ffffff;
}
.alert {
  font-size: 28rpx;
  color: #f97825;
  line-height: 40rpx;
  margin-top: 24rpx;
}
</style>
